package com.haiertvbic.tvwa;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.haiertvbic.tvwa.model.ProgramBean;
import com.haiertvbic.tvwa.model.ProgramItemBean;
import com.haiertvbic.tvwa.model.SingleHandler;
import com.haiertvbic.tvwa.network.EPGWeb;
import com.haiertvbic.tvwa.util.AppManager;
import com.haiertvbic.tvwa.util.IsExit;
import com.haiertvbic.tvwa.util.LocateToast;
import com.haiertvbic.tvwa.util.ProduceThread;
import com.haiertvbic.tvwa.util.SLog;
import com.haiertvbic.tvwa.util.SetActivityView;
import com.haiertvbic.tvwa.util.SwitchChannel;
/**
 * 获取节目数据，第二屏
 * @author sun
 *
 */
public class ChannelProActivity extends Activity {

	private static final String TAG = null;
	// 获取节目成功
	protected static final int GET_PRO_SUC = 01;
	// 获取节目失败
	protected static final int GET_PRO_FAIL = 02;
	private int cha_id;
	private int which;
	private String cha_name;
	private String[] pro_type;
	private int[] pro_id;
	private ListView cha_pro_list;
	private ArrayList<ProgramBean> pro_list;
	private List<String[]> ret_pro_list;
	public static TextView showTime_2;
	public SingleHandler sHandler;
	private ProgressBar bar_on_pro;
	public static View view;
	private boolean canToNext;
	private boolean isHide;
	private String PRO_TYPE;
	private int currentCha = -200;
	private int switchCha = -200;
	private Handler handle;
	private boolean canSwitch;
	public static ArrayList<ProgramBean> caches;

	/**
	 * 
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.channel_program);
		view = SetActivityView.setActivityView(getWindow(), getWindowManager());

		Intent intent = getIntent();
		cha_id = intent.getIntExtra("CHA_ID", -1);
		cha_name = intent.getStringExtra("CHA_NAME");

		initView();
		AppManager.activityList.add(this);

		SLog.d(TAG, "第一屏传来的频道id是：" + cha_id);
		getResultPre();
		sHandler = SingleHandler.returnHandler();
		sHandler.setTextView(showTime_2);

		handle = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case GET_PRO_FAIL:
					// 获取频道数据失败，消失加载数据进度条
					// progressDialog.dismiss();
					bar_on_pro.setVisibility(View.GONE);
					LocateToast.locateToast(ChannelProActivity.this, 200,
							"获取节目失败，请回到上一页重试，或查看网络是否连接");
					break;
				case GET_PRO_SUC:
					// 获取数据成功，适配显示数据，消失加载数据的进度条
					bar_on_pro.setVisibility(View.GONE);
					if (pro_list != null && pro_list.size() >0) {
						cha_pro_list.setAdapter(new Pro_List_Adapter(
								ret_pro_list));
					}
//					getResultAfter(ret_pro_list);
					canToNext = true;
					canSwitch = true;
					break;
				case 0:
					LocateToast.locateToast(ChannelProActivity.this, 200,
							"读取换台信息失败");
					break;

				case 4004500:
					LocateToast.locateToast(ChannelProActivity.this, 200,
							"换台成功 ");
					currentCha = switchCha;
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;

				case 4004501:
					LocateToast.locateToast(ChannelProActivity.this, 200,
							"此频道不存在");
					break;

				case 4004502:
					LocateToast.locateToast(ChannelProActivity.this, 200,
							"请插入或重新插拔CRB");
					break;

				case 4004503:
					LocateToast.locateToast(ChannelProActivity.this, 200,
							"您未设置 CRB");
					break;

				case -2002:
					LocateToast.locateToast(ChannelProActivity.this, 200,
							"连接断开");
					break;

				default:
					break;
				}

			}

		};
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		isHide = true;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (isHide)
			FavoriteChannelActivity.fView.setVisibility(View.INVISIBLE);
		if (!ProduceThread.canRun)
			view.setVisibility(View.INVISIBLE);
	}

	/**
	 * 初始化控件
	 */
	private void initView() {

		showTime_2 = (TextView) findViewById(R.id.show_time_2);
		TextView cha_name_te = (TextView) findViewById(R.id.cha_name);
		cha_pro_list = (ListView) findViewById(R.id.cha_pro_list);
		bar_on_pro = (ProgressBar) findViewById(R.id.bar_on_pro);
		cha_name_te.setText(cha_name);
		cha_pro_list.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// Toast.makeText(ChannelProActivity.this, arg2+"",
				// 1000).show();
				which = arg2;
				ProduceThread.seconds = 60;

			}

			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		cha_pro_list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (canSwitch && currentCha != cha_id) {
					SwitchChannel.switchChannel(ChannelProActivity.this,
							cha_id, handle);
					switchCha = cha_id;
				}

				ProduceThread.seconds = 60;
			}

		});
	}

	/**
	 * 
	 * @author lb
	 * 
	 */
	// private class ProAsyncTask extends AsyncTask<Integer, Void, List> {
	//
	// @Override
	// protected List doInBackground(Integer... params) {
	//
	// try {
	// SLog.d(TAG, "执行getProgramList之前");
	//
	// pro_list = EPGWeb.getProgramList(ChannelProActivity1.this,
	// cha_id);
	//
	// SLog.d(TAG, "执行doInBackground");
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// if (pro_list == null) {
	// SLog.v("lfav", "pro_list = null");
	// Looper.prepare();
	// // Toast.makeText(ChannelProActivity.this,
	// // "获取节目失败，请回到上一页重试", 1).show();
	// LocateToast.locateToast(ChannelProActivity1.this, 200,
	// "获取节目失败，请回到上一页重试");
	// Looper.loop();
	// Looper.myLooper().quit();
	// return null;
	// }
	// }
	// return getResultPre();
	// }
	//
	// @Override
	// protected void onPostExecute(List result) {
	// super.onPostExecute(result);
	// getResultAfter(result);
	// }
	//
	// }

	/**
	 * 得到节目的过程，开了一个线程和服务器交互获取数据
	 */
	public void getResultPre() {
		new Thread() {
			public void run() {
				bar_on_pro.setVisibility(View.VISIBLE);
				try {
					pro_list = EPGWeb.getProgramList(ChannelProActivity.this,
							cha_id);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				if (pro_list != null) {
					String[] pro_name = new String[pro_list.size()];
					String[] pro_time = new String[pro_list.size()];
					pro_type = new String[pro_list.size()];
					pro_id = new int[pro_list.size()];

					for (int i = 0; i < pro_list.size(); i++) {
						ProgramBean pro = pro_list.get(i);
						pro_name[i] = pro.getPn();
						SLog.v("lfav", "Pname?????????????????" + pro_name[i]);
						String s = pro.getPstime() + "c";
						// StringBuffer sb = new StringBuffer(s);
						// s = sb.reverse().toString();
						s = s.replace(":00c", "");
						pro_time[i] = s;
						SLog.v("lfav", "Ptime！！！！！！！！！！！！！！！" + pro_time[i]);
						pro_type[i] = pro.getPtype();
						SLog.v("lfav", "Ptype-----------------" + pro_type[i]);
						pro_id[i] = pro.getPid();
						SLog.v("lfav", "Pid+++++++++++++++++" + pro_id[i]);
					}

					ret_pro_list = new ArrayList<String[]>();
					ret_pro_list.add(pro_time);
					ret_pro_list.add(pro_name);
					ret_pro_list.add(pro_type);
				} else {
					handle.sendEmptyMessage(GET_PRO_FAIL);
//					Looper.prepare();
//					LocateToast.locateToast(ChannelProActivity.this, 200,
//							"获取节目失败，请回到上一页重试");
//					
//					Looper.loop();
//					Looper.myLooper().quit();
				}

				// 获取电视剧pType
				try {
					ArrayList<ProgramItemBean> itemList = EPGWeb
							.getProgramItem();
					int size = itemList.size();
					for (int index = 0; index < size; index++) {
						ProgramItemBean itemBean = itemList.get(index);
						// SLog.v("lfav", "name="+itemBean.getName());
						// SLog.v("lfav", "node="+itemBean.getNode());
						// SLog.v("lfav", "pnode="+itemBean.getPnode());
						if (itemBean.getName().equals("电视剧")) {
							// SLog.v("lfav",
							// "ppppppppppppppppppp----->找到电视剧了");
							// SLog.v("lfav", "电视剧===="+itemBean.getNode());
							PRO_TYPE = itemBean.getNode() + "";
							SLog.v("lfav", "PRO_TYPE=" + PRO_TYPE);
							break;
						}
					}
				} catch (Exception e) {
					if (PRO_TYPE == null) {
//						Looper.prepare();
//						LocateToast.locateToast(ChannelProActivity.this, 600,
//								"获取节目失败，请回到上一页重试");
//						Looper.loop();
//						Looper.myLooper().quit();
						handle.sendEmptyMessage(GET_PRO_FAIL);
					}
				}
				handle.sendEmptyMessage(GET_PRO_SUC);
			};
		}.start();

	}

	/**
	 * 得倒节目数据后往adpter里填充，为缓冲开在子线程设计
	 * 
	 * @param result
	 */
//	public void getResultAfter(List result) {
//		if (result == null) {
//			SLog.v("lfav", "结果为null");
//			LocateToast.locateToast(ChannelProActivity.this, 200,
//					"获取节目列表失败，请退出重试");
//			return;
//		}
//		// String[] string = (String[]) result.get(0);
//		// Log.v("fav", string[0]);
//		// Toast.makeText(ChannelProActivity.this, string[0], 10000).show();
//		canToNext = true;
//		cha_pro_list.setAdapter(new Pro_List_Adapter(
//				result));
//		bar_on_pro.setVisibility(View.GONE);
//		canSwitch = true;
//	}

	/**
	 * 
	 * @author lb
	 * 
	 */
	private class Pro_List_Adapter extends BaseAdapter {
		private List result;

		public Pro_List_Adapter( List result) {
			this.result = result;
			// TODO Auto-generated constructor stub
		}

		public int getCount() {
			SLog.v("lfav", "pro_list = " + pro_list.size());
			return pro_list.size();
			// return 10;
		}

		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int arg0, View arg1, ViewGroup arg2) {
			SLog.v("lfav", "getView");
			// ViewHolder viewHolder;
			// if(arg1 == null) {
			// arg1 =
			// LayoutInflater.from(ChannelProActivity.this).inflate(R.layout.cha_pro_list_item,
			// null);
			// viewHolder = new ViewHolder();
			// viewHolder.pro_name = (TextView)
			// arg1.findViewById(R.id.pro_name);
			// viewHolder.pro_time = (TextView)
			// arg1.findViewById(R.id.play_time);
			// viewHolder.to_next = (TextView) arg1.findViewById(R.id.toNext);
			//
			// arg1.setTag(viewHolder);
			// }
			// else{
			// viewHolder = (ViewHolder) arg1.getTag();
			// }
			// viewHolder.pro_name.setText(ret_pro_list.get(1)[arg0]);
			// SLog.v("lfav", "pro_name="+ret_pro_list.get(1)[arg0]);
			// viewHolder.pro_time.setText(ret_pro_list.get(0)[arg0]);
			// SLog.v("lfav", "pro_time="+ret_pro_list.get(0)[arg0]);
			//
			// if (!pro_type[arg0].contains(PRO_TYPE)) {
			// SLog.v("lfav", arg0+"条不是电视剧");
			// // to_next.setTextColor(Color.GRAY);
			// viewHolder.to_next.setVisibility(View.INVISIBLE);
			// }
			// else{
			// viewHolder.to_next.setVisibility(View.VISIBLE);
			// }
			// return arg1;

			if (arg1 == null) {
				arg1 = LayoutInflater.from(ChannelProActivity.this).inflate(
						R.layout.cha_pro_list_item, null);
			}
			TextView pro_name = (TextView) arg1.findViewById(R.id.pro_name);
			TextView pro_time = (TextView) arg1.findViewById(R.id.play_time);
			TextView to_next = (TextView) arg1.findViewById(R.id.toNext);

			pro_name.setText(ret_pro_list.get(1)[arg0]);
			SLog.v("lfav", "pro_name=" + ret_pro_list.get(1)[arg0]);
			pro_time.setText(ret_pro_list.get(0)[arg0]);
			SLog.v("lfav", "pro_time=" + ret_pro_list.get(0)[arg0]);

			if (!pro_type[arg0].contains(PRO_TYPE)) {
				SLog.v("lfav", arg0 + "条---不是---电视剧");
				// to_next.setTextColor(Color.GRAY);
				to_next.setVisibility(View.INVISIBLE);
			} else {
				SLog.v("lfav", arg0 + "条---是---电视剧");
				to_next.setVisibility(View.VISIBLE);
			}
			return arg1;

		}
	}

	/**
	 * 处理按键事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		ProduceThread.seconds = 60;
		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			sHandler.setTextView(FavoriteChannelActivity.showTime_1);
			finish();
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			// Toast.makeText(ChannelProActivity.this, "DPAD_BACK",
			// 1000).show();
			ProduceThread.canRun = false;
			ProduceThread.exit = false;
			IsExit.isExit(this);
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
//			if (ret_pro_list != null) {}

			if (pro_list !=null &&canToNext && pro_list.size() > 0) {

				if (pro_type[which].contains(PRO_TYPE)) {
					Intent intent = new Intent();
					intent.setClass(ChannelProActivity.this,
							ProChannelActivity.class);
					intent.putExtra("PRO_ID", pro_id[which]);
					intent.putExtra("PRO_NAME", ret_pro_list.get(1)[which]);
					SLog.v("fav", "PID*****************************"
							+ pro_id[which]);
					startActivity(intent);
					view.setVisibility(View.INVISIBLE);
				} else {
					// Toast toast = Toast.makeText(ChannelProActivity.this,
					// "当前节目不是电视剧，无相关数据", 1000);
					// View toastView =
					// LayoutInflater.from(ChannelProActivity.this).inflate(R.layout.toast_layout,
					// null);
					// TextView v = (TextView)
					// toastView.findViewById(R.id.content);
					// toast.setView(toastView);
					// int toastWidth = v.getLayoutParams().width;
					// SLog.v("lfav", "toast.getView()="+toast.getView());
					// SLog.v("lfav", "toastWidth="+toastWidth);
					// int displayWidth =
					// ChannelProActivity.this.getWindowManager().getDefaultDisplay().getWidth();
					// toast.setGravity(Gravity.RIGHT|Gravity.BOTTOM,
					// (displayWidth/8)-(toastWidth/2), 80);
					// toast.show();
					LocateToast.locateToast(this, 200, "当前节目不是电视剧，无相关数据");

				}
			}
		
		}
		return super.onKeyDown(keyCode, event);
	}

}
